package com.xuecheng.govern.gateway.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 从请求头 Authorization 中获取jwt令牌
     * 该请求头的值格式 ->  {bearer jwt令牌}
     * @param request
     * @return
     */
    public String getJwtTokenFromHeader(HttpServletRequest request) {
        String authorizationValue = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorizationValue)) {
            return null;
        }
        if (!authorizationValue.startsWith("Bearer")) {
            return null;
        }
        return authorizationValue.split(" ")[1];
    }

    /**
     * 根据用户短令牌从redis中查找jwt令牌(access_token)
     * @param jti_token
     * @return
     */
    public long getExpireOfToken(String jti_token) {
        String key = "user_token:" + jti_token;
        //如果过期, 返回值为-2
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        //如果查不到
        return expire;
    }

    /**
     * 从cookie中获取用户短令牌
     * @param request
     * @return
     */
    public String getTokenFromCookie(HttpServletRequest request){
        //该map集合中,key为cookie的name, value为cookie的value
        Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
        String jti_token = cookieMap.get("uid");
        if(StringUtils.isEmpty(jti_token)){
            return null;
        }
        return jti_token;
    }
}
